package com.pay.service.impl;

import java.math.BigDecimal;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pay.constant.Constant;
import com.pay.entity.MerchantAccount;
import com.pay.entity.MerchantAccountDetail;
import com.pay.exception.ServiceException;
import com.pay.mapper.MerchantAccountMapper;
import com.pay.service.IMerchantAccountDetailService;
import com.pay.service.IMerchantAccountService;
import com.pay.utils.FunctionUtils;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Peng
 * @since 2018-12-10
 */
@Service
public class MerchantAccountServiceImpl extends ServiceImpl<MerchantAccountMapper, MerchantAccount> implements IMerchantAccountService {

	private Lock lock = new ReentrantLock() ;

	@Autowired
	private IMerchantAccountDetailService merchantAccountDetailService ;
	
	@Override
	public String insertAccountDetail(Integer merchantId, Integer typeid, Integer isout, BigDecimal cost,String remark) {
		String result="";
		try {
			lock.lock();
			MerchantAccount merchantAccount = super.getOne(new QueryWrapper<MerchantAccount>().eq("mer_id", merchantId));
			BigDecimal originalPoint=merchantAccount.getMoney();
			BigDecimal point=merchantAccount.getMoney();
			if(FunctionUtils.isEquals(Constant.pay_in,isout)){
				point=FunctionUtils.add(point, cost, 2);
			}else{
				point=FunctionUtils.sub(point, cost, 2);
			}
			merchantAccount.setMoney(point);
			//首先修改积分 根据当前版本号去修改
			boolean i = super.updateById(merchantAccount) ;
			if(!i) {
				throw new ServiceException("更新商户金额异常") ;
			}
			MerchantAccountDetail details = new MerchantAccountDetail();
			details.setMerId(merchantId);
			details.setTypeid(typeid);
			details.setIsout(isout);
			details.setOriginal(originalPoint);
			details.setCost(cost);
			details.setLast(point);
			details.setRemark(remark);
			i = merchantAccountDetailService.save(details);
			if(!i) {
				throw new ServiceException("添加商户金额明细失败") ;
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("保存校验用户积分异常");
		} finally {
			lock.unlock();
		}
		return result;
	}

	@Override
	public MerchantAccount getByMerId(Integer id) {
		return super.getOne(new QueryWrapper<MerchantAccount>().eq("mer_id", id)) ;
	}

}
